#include"queue.h"

void QueueInit(Queue* pq)
{
	assert(pq);

	pq->head = NULL;
	pq->tail = NULL;
}

void QueueDestory(Queue* pq)
{
	assert(pq);

	QueueNode* cur = pq->head;
	while (cur)
	{
		QueueNode* next = cur->next;
		free(cur);
		cur = next;
	}
	pq->head = NULL;
	pq->tail = NULL;
}

void QueuePush(Queue* pq, QDataType x) 
{
	assert(pq);

	QueueNode* NewNode = (QueueNode*)malloc(sizeof(QueueNode) * 1);
	NewNode->data = x;
	NewNode->next = NULL;
	// 没有节点
	if (pq->head == NULL && pq->tail == NULL)
	{
		pq->head = pq->tail = NewNode;
	}
	// 尾插
	else
	{
		pq->tail->next = NewNode;
		pq->tail = NewNode;
	}
}

void QueuePop(Queue* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));

	QueueNode* next = pq->head->next;
	free(pq->head);
	pq->head = next;
	// 最后一个节点删除，tail还指向最后一个节点
	if (pq->head == NULL)
		pq->tail = NULL;
}

QDataType QueueFront(Queue* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));
	return pq->head->data;
}
QDataType QueueBack(Queue* pq)
{
	assert(pq);
	assert(!QueueEmpty(pq));
	return pq->tail->data;
}

size_t QueueSize(Queue* pq)
{
	assert(pq);
	QueueNode* cur = pq->head;
	size_t count = 0;
	while (cur)
	{
		count++;
		cur = cur->next;
	}
	return count;
}

bool QueueEmpty(Queue* pq)
{
	assert(pq);
	return pq->head == NULL;
}